import Taro, { getCurrentInstance } from '@tarojs/taro'
import React, { Component, useEffect } from 'react'
import { View, Text, Image } from '@tarojs/components'
import api from '@/api'
import {
  requestCallback,
  qwsdk,
  setWeapp,
  isFromWebapp,
  navigateTo,
  cleanWeapp,
  VERSION_PLATFORM,
  VERSION_STANDARD,
  isIos
} from '@/utils'
import { SpToast, SpModal } from '@/components'
import { connect } from 'react-redux'

import S from '@/spx'
import './index.scss'
import { stringify } from 'qs'
import { updateMessageNum, updateToday_data } from '@/store/user'
import { updateQRCode, setupdateQRCode } from '@/store/qrcode'
@connect(({ planSelection, user, qrcode }) => ({
  planSelection: planSelection.activeShop,
  userInfo: user.userInfo,
  messageNum: user.messageNum,
  realTimeData: user.today_data,
  qrcode: qrcode.qrcode,
  codestr: qrcode.codestr
}),
  {updateMessageNum: updateMessageNum,
    updateToday_data:updateToday_data,
  setupdateQRCode: setupdateQRCode,}
)
// @withLogin()
class Index extends Component {
  constructor(props) {
    super(props)
    this.state = {
      moneyShow: true,
      realTimeDataApp: {
        real_payed_fee: 0, //  实付金额
        real_payed_orders: 0, // 支付订单数
        real_payed_members: 0, // 实付会员数
        real_atv: 0, // 客单价
        real_refunded_fee: 0, //退款金额
        real_aftersale_count: 0, //售后订单数
        real_deposit: 0 // 新增储蓄
      },
      loading: true,
      apis: {
        aftersales: '',
        order: '',
        items: undefined,
        order_ziti: undefined
      },
      is_center: false,
      currentModal: {
        visible: '',
        status: '',
        shopList: [],
        order_info: {}
      },
      yesterday_data: {
        real_payed_fee: 0, //  实付金额
        real_payed_orders: 0, // 支付订单数
        real_payed_members: 0, // 实付会员数
        real_atv: 0, // 客单价
        real_refunded_fee: 0, //退款金额
        real_aftersale_count: 0, //售后订单数
        real_deposit: 0 // 新增储蓄
      },
      notice_data: {},

      barcode: null
    }
  }
  async componentDidMount() {
    console.log('componentDidMount-------')
    S.getLoginType()
    if (!S.getLoginType()) {
      console.log('componentDidMount-------11111')
      await Taro.setTabBarItem({
        index: 0,
        text: '商家',
      })
      await Taro.setTabBarItem({
        index: 1,
        text: '店铺',
        iconPath: './assets/imgs/index/shop.png',
        selectedIconPath: './assets/imgs/index/shopHover.png',
      })
    } else {
      console.log('componentDidMount-------22222')
      await Taro.setTabBarItem({
        index: 0,
        text: '店铺',
      })
      await Taro.setTabBarItem({
        index: 1,
        text: '消息',
        iconPath: './assets/imgs/index/message.svg',
        selectedIconPath: './assets/imgs/index/messageHover.svg',
      })
    }
    if (S.getAuthToken()) {
      Taro.getApp().addsoct()
    } else {
      Taro.reLaunch({ url: `/pages/auth/login` })
    }
  }

  async componentWillUnmount() {

  }
  async componentDidShow() {
    console.log('componentDidShow-------')
    // setWeapp()
    // if (isFromWebapp()) {
    //   const { app_id, app_type, company_id, openid, unionid, token } = S.get('WEBAPP', true)
    //   // let data
    // const {
    //   router: {
    //     params: { qr_result }
    //   }
    // } = getCurrentInstance()
    
    if (this.props.qrcode) {

      console.log('qr_result=========', this.props.codestr)
      this.tohexiao(this.props.codestr)
      this.props.setupdateQRCode()
    }

    if (S.getAuthToken()) {

      this.getConfig(S.getLoginType())


      // this.zitiWebsocket()


    } else {
      Taro.redirectTo({ url: `/pages/auth/login` })
    }
  }

  async getConfig(type) {
    const { messageNum, realTimeData } = this.props

    let { distributor_id } = this.props.planSelection
    let is_app = ''
    console.log(type)
    if (!type) {
      distributor_id = ''
      is_app = ''
    }else{
      is_app = 1
    }
    if (distributor_id != null) {
      const result = await api.home.getStatistics({ shop_id: distributor_id,is_app: type })
      // await dispatch(updateToday_data(result.today_data))
      await this.props.updateToday_data(result.today_data)
      this.setState({
        realTimeData: realTimeData,
        realTimeDataApp: result.today_data,
        notice_data: result.notice_data,
        yesterday_data: result.yesterday_data,
        apis: result.apis
      })
    } else {
      Taro.redirectTo({ url: `/pages/planSelection/index` })
    }
    if (!!type) {
      const result = await api.message.getMessageList({ distributor_id })
      const { num_type_1, num_type_2, num_type_3 } = result
      let num = Number(num_type_1 ? num_type_1 : 0) + Number(num_type_2 ? num_type_2 : 0) + Number(num_type_3 ? num_type_3 : 0)
      console.log('----num',num)
      // await dispatch(updateMessageNum(num.toString()))
      await this.props.updateMessageNum(num.toString())
    } else {
      // const { aftersales_count, refund_errorlogs_count, wait_delivery_count } = this.state.notice_data
      // let num = Number(aftersales_count ? aftersales_count : 0) + Number(refund_errorlogs_count ? refund_errorlogs_count : 0) + Number(wait_delivery_count ? wait_delivery_count : 0)
      // await dispatch(updateMessageNum(num.toString()))
    }

  }
  async switchHandle() {
    this.setState({
      moneyShow: !this.state.moneyShow
    })
  }
  goOrderPageHandle() {
    Taro.navigateTo({
      url: '/pages/order/list'
    })
  }

  goAfterSalesPageHandle = () => {
    Taro.navigateTo({
      url: '/pages/afterSales/list'
    })
  }

  formatA(num) {
    var result = parseFloat(num)
    if (isNaN(result)) {
      console.log('传递参数错误，请检查！')
      return false
    }
    result = Math.round(num * 100) / 100
    var s_x = result.toString()
    var pos_decimal = s_x.indexOf('.')
    if (pos_decimal < 0) {
      pos_decimal = s_x.length
      s_x += '.'
    }
    while (s_x.length <= pos_decimal + 2) {
      s_x += '0'
    }
    return s_x
  }

  tohexiao = async (res) => {
    // const res = 'excode:65796-2124869866'
    // console.log('code', res)
    const str = 'excode:'
    if (res && res.indexOf(str) == -1) {
      requestCallback(
        async () => {
          const data = await api.order.qrwriteoff({
            code: res.replace('ZT_', '')
          })
          return data
        },
        '核销订单成功',
        ({ order_id }) => {
          Taro.navigateTo({ url: `/pages/order/detail?order_id=${order_id}` })
        },
        () => {
          // S.toast('核销码不存在或有误，请检查！')
          this.setState({
            veriError: '核销码不存在或有误，请检查！'
          })
        }
      )
    } else if (res && res.indexOf(str) != -1) {
      let { distributor_id } = this.props.planSelection
      try {
        const result = await api.home.checkCode({
          code: res.slice(7),
          distributor_id
        })
        if (!result.status) {
          this.setState({
            currentModal: {
              visible: true,
              status: 'fail',
              shopList: result.distributors.list
            }
          })
        } else {
          this.setState({
            currentModal: {
              visible: true,
              status: 'success',
              order_info: result.order_info.items
            }
          })
        }
      } catch (error) {
        // S.toast('核销码不存在或有误，请检查！')
        this.setState({
          veriError: '核销码不存在或有误，请检查！'
        })
      }
    }
  }

  handleOnScanQRCode = async () => {
    console.log('clicl:handleOnScanQRCode')
    // this.createBarcode()
    // const res = await qwsdk.scanQRCode()
    Taro.navigateTo({ url: `/pages/order/scanQRCode/index` })
    // const res = 'excode:65796-2124869866'
    // console.log('code', res)
    const str = 'excode:'

  }
  handleCancel = () => {
    this.setState({
      currentModal: {
        visible: '',
        status: '',
        shopList: [],
        order_info: {}
      }
    })
  }
  // 查看订单详情
  orderInfoHandle = (order_id) => {
    Taro.navigateTo({ url: `/pages/order/detail?order_id=${order_id}` })
  }

  render() {
    const { moneyShow, loading, apis, is_center, currentModal, realTimeDataApp, yesterday_data } = this.state

    let { name, logo, distributor_id } = this.props.planSelection
    const loginType = S.getLoginType()
    console.log('loginTypeetwq34===',loginType)
    if (!loginType) {
      let { merchant_name, head_portrait } = this.props.userInfo
    }
    let { realTimeData } = this.props
    if (!realTimeData) {
      realTimeData = realTimeDataApp
    }
    return (
      <View className='page-index'>
        <>
          <View>
            <View className='top'>
              <View className='shop-title'>
                <View className='avatar'>
                  <Image className='photo' src={loginType ? logo : head_portrait}></Image>
                </View>
                <View className='title'>{loginType ? name : merchnat_name}</View>
              </View>
            </View>
            <Image
              className='info-img'
              src={require('@/assets/imgs/index/bg.png')}
            ></Image>
            <View className='current-status'>
              <View className='big-title'>
                {/* <View className='iconfont icon-gaikuang'></View> */}
                <View className='img_'>
                  <Image className='img' src={require('@/assets/imgs/index/shishigaikuang.png')}></Image>
                </View>
                <Text className='title'>实时概况</Text>
              </View>
              <View className='spend-money'>
                <View className='title'>
                  <Text>实付金额（元）</Text>
                  {moneyShow ? (
                    <View className='img_' onClick={() => {
                      this.switchHandle()
                    }}>
                      <Image className='img' src={require('@/assets/imgs/index/yincang.png')}></Image>
                    </View>
                  ) : (
                    <View className='img_' onClick={() => {
                      this.switchHandle()
                    }}>
                      <Image className='img' src={require('@/assets/imgs/index/xianshi.png')}></Image>
                    </View>
                  )}
                </View>
                <View className='money'>
                  {moneyShow ? (
                    <>
                      <Text>{this.formatA(realTimeData.real_payed_fee / 100)}</Text>
                      {!loginType && (<Text className='yesterdata'>昨日:{this.formatA(yesterday_data.real_payed_fee / 100)}</Text>)}
                    </>
                  ) : (
                    <Text>****</Text>
                  )}

                </View>
              </View>
              <View className='list'>
                <View className='pay-order'>
                  <View className='title'>支付订单（笔）</View>
                  <View className='color-white'>
                    <View>{realTimeData.real_payed_orders}</View>
                    {!loginType && (<View className='color-white-yes'>昨日:{this.formatA(yesterday_data.real_payed_orders)}</View>)}
                  </View>


                </View>
                <View className='pay-order'>
                  <View className='title'>售后订单（笔）</View>
                  <View className='color-white'>
                    <View>{realTimeData.real_aftersale_count}</View>
                    {!loginType && (<View className='color-white-yes'>昨日:{this.formatA(yesterday_data.real_aftersale_count)}</View>)}
                  </View>
                </View>
              </View>

              <View className='list list-2'>
                <View className='pay-order'>
                  <View className='title'>退款（元）</View>

                  <View className='color-gray'>
                    <View>{this.formatA(realTimeData.real_refunded_fee / 100)}</View>
                    {!loginType && (<View className='color-gray-yes'>昨日:{this.formatA(realTimeData.real_refunded_fee / 100)}</View>)}
                  </View>
                </View>
                <View className='pay-order'>
                  <View className='title'>实付会员（人）</View>
                  <View className='color-gray'>
                    <View>{realTimeData.real_payed_members}</View>
                    {!loginType && (<View className='color-gray-yes'>昨日:{realTimeData.real_payed_members}</View>)}
                  </View>
                </View>
              </View>
              <View className='list list-2'>
                <View className='pay-order'>
                  <View className='title'>客单价（元）</View>
                  <View className='color-gray'>
                    <Text>{this.formatA(realTimeData.real_atv / 100)}</Text>
                    {!loginType && (<Text className='color-gray-yes' style='margin-left: 10px;'>昨日:{this.formatA(realTimeData.real_atv / 100)}</Text>)}
                  </View>
                </View>
              </View>
            </View>
          </View>

          <View className='func-list'>
            <View className='title'>常用功能</View>
            <View className='list'>
              {!loginType && (<View className='item' onClick={() => navigateTo('/pages/shop')}>
                <View>
                  <Image className='img' src={require('@/assets/imgs/index/dianpu.png')}></Image>
                </View>
                <View className='subtitle'>店铺管理</View>
              </View>)}
              <View className='item' onClick={() => navigateTo('/pages/good/list')}>
                <View>
                  <Image className='img' src={require('@/assets/imgs/index/good.png')}></Image>
                </View>
                <View className='subtitle'>商品管理</View>
              </View>
              <View className='item' onClick={this.goOrderPageHandle}>
                <View>
                  <Image className='img' src={require('@/assets/imgs/index/dingdan.png')}></Image>
                </View>
                <View className='subtitle'>订单管理</View>
              </View>
              <View className='item' onClick={this.goAfterSalesPageHandle}>
                <View>
                  <Image className='img' src={require('@/assets/imgs/index/shouhou.png')}></Image>
                </View>
                <View className='subtitle'>售后管理</View>
              </View>
              {!!loginType && (<View className='item' onClick={this.handleOnScanQRCode.bind(this)}>
                <View className='img_'>
                  <Image
                    className='img'
                    src={require('@/assets/imgs/index/shaoyishao.png')}
                  ></Image>
                </View>
                <View className='subtitle'>扫码核销</View>
              </View>)}
              <View className='item' onClick={() => navigateTo('/pages/order/ziti-list')}>
                <View className='img_'>
                  <Image className='img' src={require('@/assets/imgs/ziti-order.png')}></Image>
                </View>
                <View className='subtitle'>自提订单</View>
              </View>
              {!!loginType && (<View className='item' onClick={() => navigateTo('/pages/coupon/list')}>
                <View className='img_'>
                  <Image className='img' src={require('@/assets/imgs/ziti-order.png')}></Image>
                </View>
                <View className='subtitle'>优惠券</View>
              </View>)}
              {!loginType && (<View className='item' onClick={() => navigateTo('/pages/peopleMana')}>
                <View>
                  <Image className='img' src={require('@/assets/imgs/index/renyuanguanli.png')}></Image>
                </View>
                <View className='subtitle'>人员管理</View>
              </View>)}
              {/* {VERSION_STANDARD && (
                <View
                  className='item'
                  onClick={() => {
                    wx.miniProgram.navigateTo({
                      url: `/subpages/dianwu/list?token=${S.getAuthToken()}&distributor_id=${distributor_id}`
                    })
                  }}
                >
                  <View className='img_'>
                    <Image
                      className='img'
                      src={require('@/assets/imgs/icon_goods_search.png')}
                    ></Image>
                  </View>
                  <View className='subtitle'>商品查询</View>
                </View>
              )} */}
              {/* {VERSION_STANDARD && (
                <View
                  className='item'
                  onClick={() => {
                    wx.miniProgram.navigateTo({
                      url: `/subpages/dianwu/cashier?token=${S.getAuthToken()}&distributor_id=${distributor_id}`
                    })
                  }}
                >
                  <View className='img_'>
                    <Image className='img' src={require('@/assets/imgs/icon_cashier.png')}></Image>
                  </View>
                  <View className='subtitle'>收银台</View>
                </View>
              )} */}
              {/* {VERSION_STANDARD && (
                <View
                  className='item'
                  onClick={() =>
                    wx.miniProgram.navigateTo({
                      url: `/subpages/dianwu/pending-checkout?token=${S.getAuthToken()}&distributor_id=${distributor_id}&from=home`
                    })
                  }
                >
                  <View className='img_'>
                    <Image
                      className='img'
                      src={require('@/assets/imgs/icon_fetch_order.png')}
                    ></Image>
                  </View>
                  <View className='subtitle'>取单</View>
                </View>
              )} */}

              <SpToast />
            </View>
          </View>
          <SpModal
            currentModal={currentModal}
            handleCancel={this.handleCancel}
            orderInfoHandle={this.orderInfoHandle}
          ></SpModal>
        </>
      </View>
    )
  }
}
export default Index
